import { createRouter, createWebHistory } from 'vue-router'

// 引入组件
import Login from '@/views/framework/login/index.vue'
import Home from '@/views/framework/home/index.vue'
import Myself from '@/views/framework/myself/index.vue'
import Layout from '../layout/index.vue'
import Error from '@/views/framework/404/index.vue'

import tool from '../utils/tool.js'
import XEUtils from 'xe-utils'

const routes = [
  {
    path: '/',
    name: 'login',
    component: Login,
  },
  {
    path: '/layout',
    name: 'Layout',
    component: Layout,
    redirect: '/home',
    children: []
  },
  {
    path: '/_home',
    component: Layout,
    children: [
      {
        path: '/home',
        name: 'Home',
        component: Home
      },
      {
        path: '/myself',
        name: 'Myself',
        component: Myself
      }
    ]
  },
  {
    path: '/:catchAll(.*)',
    name: 'error',
    component: Layout,
    children: [
      {
        path: '/:catchAll(.*)',
        name: '404',
        component: Error
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 获取当前路由列表
router.getAllMenus = function () {
  const apiMenus = tool.session.get('menus')
  let menus = []
  if (apiMenus) { 
    menus = filterAsyncRouter(JSON.parse(apiMenus))
  }
  return menus
}

var isGetRouter = false
const routeWhiteList = ['/']

// 全局前置路由守卫-初始化、每次路由切换之前被调用
router.beforeEach((to, from) => {

  // 登录页面
  if (to.path == '/') {
    isGetRouter = false
  }

  // 判断token，没有token时跳转至登录页
  let token = tool.session.get('token')
  if (!token && routeWhiteList.indexOf(to.path) === -1) {
    return {path: '/'}
  }

  // 加载动态路由
  if (!isGetRouter) {
    // 得到接口得到的动态路由
    const apiMenus = tool.session.get('menus')
    // 处理动态路由
    if (apiMenus != null && apiMenus.length != 0) {
      const menus = filterAsyncRouter(JSON.parse(apiMenus))
      const menuRouter = XEUtils.toTreeArray(menus) // 扁平化路由

      menuRouter.forEach(item => {
        router.addRoute('Layout', item)
      })

      isGetRouter = true

      // 处理刷新后空白页面的问题
      if (to.name === '404') {
        router.push(to.path)
      }
    }
  }
})

function filterAsyncRouter (routerMap) {
  const accessedRoutes = []
  routerMap.forEach(item => {
    // 路由对象
    let route = {
      path: item.path,
      name: item.name,
      component: loadComponent(item.url + '/index.vue'),
      children: item.children ? filterAsyncRouter(item.children) : undefined // 遍历子集目录
    }
    accessedRoutes.push(route)
  })
  return accessedRoutes
}

const modules = import.meta.glob('/src/views/*/*/*.vue')
function loadComponent (url) {
  return modules[`/${url}`] || modules['/src/views/framework/404/index.vue']
}

export default router
